<template>
  <view>
    <view class="search-box">
      <uni-search-bar
        @input="input"
        :radius="100"
        cancelButton='none'
        focus
        v-model="searchVal"
      ></uni-search-bar>
    </view>
    <!-- 搜索建议 -->
    <view class="sugg-list" v-if="searchVal.trim() !== ''">
      <view class="sugg-item" v-for="(item, index) in searchList" :key="item.id" @click="gotoDetail(item.id)">
        <view class="goods_name">{{ item.goods_name }}</view>
        <uni-icons type="arrowright" size="16"></uni-icons>
      </view>
    </view>
    <!-- 搜索历史 -->
    <view class="search-history" v-else>
      <view class="history-title">
        <text>搜索历史</text>
        <uni-icons type="trash" size="17" @click="clearHistory"></uni-icons>
      </view>
      <!-- 列表区域 -->
      <view class="history-list">
        <uni-tag
          v-for="(item, index) in searchHistory"
          :key="index"
          :text="item"
          inverted
          circle
          @click="tagClick(item)"
        />
      </view>
    </view>
  </view>
</template>

<script setup>
import { onLoad  } from '@dcloudio/uni-app'
import { ref, nextTick } from 'vue';  
import * as mockData from '../../api/mock.js'
  
  let searchVal = ref(''); // 搜索关键字
  let timer = ref(null); // 防抖变量
  // 查询的搜索建议列表
  let searchList = ref([]);
  // 搜索历史
  let searchHistory = ref([])

  // 搜索文本改变时触发
  function input(e) {
    searchVal.value = e;
    clearTimeout(timer.value);
    timer.value = setTimeout(()=>{
      getSearchList(e);
    }, 500)
  }
  async function getSearchList(e) {
    if(e.trim() === '') {
      searchList.value = [];
      return;
    }
    // const { data: res } = await uni.$http.get('/api/public/v1/good/qsearch', { query: e });
    // if(Object.prototype.toString.call(res) !== '[object Object]' || res?.meta?.status !== 200) {
    //   // uni.$showMsg方法在main中封装
    //   return uni.$showMsg();
    // }
    // searchList.value = res.message;
    searchList.value = mockData.searchResList;
    
    // 如果搜索历史中不包含搜索关键字，将搜索关键字头部插入
    if(!searchHistory.value.includes(e.trim())) {
      searchHistory.value.unshift(e.trim());
      // 如果搜索历史中包含搜索关键字，将搜索关键字挪到最前面展示
    } else {
      let i = searchHistory.value.findIndex(item => item === e.trim());
      let arr = searchHistory.value.filter((item, index) => index !== i);
      arr.unshift(e.trim());
      searchHistory.value = arr;
    }
    // 本地存储
    uni.setStorageSync('searchHistory', JSON.stringify(searchHistory.value));
  }
  function gotoDetail(id) {
    uni.navigateTo({
      url: `/subpkg/goods_detail/goods_detail?goods_id=${id}`
    })
  }
  // 点击搜索历史tag
  function tagClick(item) {
    console.log('点击搜索历史', item);
    uni.navigateTo({
      url: `/subpkg/goods_list/goods_list?query=${item}`
    })
  }
  onLoad(() => {
    // 获取本地存储
    searchHistory.value = JSON.parse(uni.getStorageSync('searchHistory') || "[]");
  })
  // 清空历史记录
  function clearHistory() {
    // uni.removeStorageSync('searchHistory');
    uni.setStorageSync('searchHistory', "[]")
    searchHistory.value = [];
  }
  
  
  
</script>

<style lang="scss" scoped>
.search-box {
  background-color: #2faf63;
  position: sticky;
  top: 0;
  z-index: 1;
}

.sugg-list {
  padding: 0 5px;
  .sugg-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 12px;
    padding: 13px 0;
    border-bottom: 1px solid #efefef;
    .goods_name {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      margin-right: 8px;
    }
  }
}

.search-history {
  padding: 0 5px;
  .history-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 40px;
    font-size: 13px;
    border-bottom: 1px solid #efefef;
  }
  
  .history-list {
    display: flex;
    flex-wrap: wrap;
    uni-tag {
      margin: 5px 5px 0 0;
    }
  }
}

</style>
